package org.dromara.system.executor;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.system.domain.AlarmIndicator;
import org.dromara.system.domain.bo.IndicatorPushBo;
import org.dromara.system.mapper.AlarmIndicatorMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class DataExecutorService {

    @Value("${indicator.data.transform}")
    private String on;

    /**
     * 数据集key值
     */
    @Value("${indicator.push.data-set:indicator}")
    private String dataSet;

    private final AlarmIndicatorMapper alarmIndicatorMapper;

    private final StringRedisTemplate stringRedisTemplate;

    public void pushToDataFromDataPlatform() {
        if (!"ON".equals(on)) {
            return;
        }
        List<AlarmIndicator> list = alarmIndicatorMapper.selectList();

        //TODO 查询设施风险等级, 冲风险分区模块查询
        if (!CollectionUtils.isEmpty(list)) {
            int count = 0;
            for (AlarmIndicator indicator : list) {
                IndicatorPushBo indicatorPushBo = new IndicatorPushBo();
                BeanUtils.copyProperties(indicator, indicatorPushBo);
                indicatorPushBo.setIndicatorName(indicator.getName());
                String key = indicatorPushBo.getCollectorId() + indicatorPushBo.getSysNum();
                String value = JsonUtils.toJsonString(indicatorPushBo);
                if (value != null) {
                    stringRedisTemplate.opsForHash().put(dataSet, key, value);
                    count++;
                } else {
                    log.warn("监测点位数据JSON转换失败，indicatorId: {}", indicator.getId());
                }
            }
            log.info("本次共加载点位数据{}条", count);
        }
    }
}
